package com.leaf.u.basehttp.download;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public final class Response {
	private final int code;
	private final Headers headers;
	private final long contentLength;
	private final InputStream inputStream;

	private Response(Builder builder) {
		this.code = builder.code;
		this.headers = builder.headers;
		this.contentLength = builder.contentLength;
		this.inputStream = builder.inputStream;
	}

	public int code() {
		return this.code;
	}

	public Headers headers() {
		return this.headers;
	}

	public long contentLength() {
		return this.contentLength;
	}

	public InputStream inputStream() {
		return this.inputStream;
	}

	public String header(String name) {
		return header(name, null);
	}

	public String header(String name, String defaultValue) {
		String result = headers.get(name);
		return result != null ? result : defaultValue;
	}

	public String string() {
		if (inputStream == null) {
			return null;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		try {
			while ((i = inputStream.read()) != -1) {
				baos.write(i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return baos.toString();
	}

	public static class Builder {
		private int code;
		private Headers headers;
		private long contentLength;
		private InputStream inputStream;

		public Response build() {
			return new Response(this);
		}

		public Builder setCode(int code) {
			this.code = code;
			return this;
		}

		public Builder setHeaders(Headers headers) {
			this.headers = headers;
			return this;
		}

		public Builder setContentLength(long contentLength) {
			this.contentLength = contentLength;
			return this;
		}

		public Builder setInputStream(InputStream inputStream) {
			this.inputStream = inputStream;
			return this;
		}
	}

}
